import { Message } from 'element-ui';
import api from './api.js';

/**
 * 格式化日期
 * @param {Object} date 
 */
function formatTime(date) {
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()

    var hour = date.getHours()
    var minute = date.getMinutes()
    var second = date.getSeconds()


    return [year, month, day].map(_normalizeNumber).join('-') + ' ' + [hour, minute, second].map(_normalizeNumber).join(':')
}

function _normalizeNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
}


/**
 * 格式化数字
 * @param {!number} number 要格式化的数字
 * @param {!number} decimals 保留几位小数
 * @param {string} dec_point 小数点符号
 * @param {string} thousands_sep 千分位符号
 * @param {string} [roundtag=ceil] 舍入参数，默认 "ceil"：向上取；"floor"：向下取；"round"：四舍五入。
 */
function formatNumber(number, decimals, dec_point, thousands_sep,roundtag) {
    number = (number + '').replace(/[^0-9+-Ee.]/g, '');
    roundtag = roundtag || "ceil"; //"ceil","floor","round"
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {

            var k = Math.pow(10, prec);

            return '' + parseFloat(Math[roundtag](parseFloat((n * k).toFixed(prec*2))).toFixed(prec*2)) / k;
        };
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    var re = /(-?\d+)(\d{3})/;
    while (re.test(s[0])) {
        s[0] = s[0].replace(re, "$1" + sep + "$2");
    }

    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

/**
 * 安全解析json字符串，避免抛出异常（字符串格式错误时，返回空对象）
 * @param {String} str 要解析的字符串
 */
function safeParseJson(str) {
    let result = null;
    try {
        result = JSON.parse(str);
    }
    catch(e)
    {
        result = new Object;
        console.log("ERROR ==> Invalid json string:" , str);
    }
    return result;
}


/**
 * 处理字符串，如果字符串为空或未定义，则返回默认值，否则返回字符串本身
 * @param {Stirng} s 要处理的字符串
 * @param {String} dflt 如果字符串为空或未定义，返回的默认值
 */
function handleNullStr(s, dflt = "") {
    if (s == null || s == undefined) {
        return dflt;
    }
    return s;
}

/**
 * 隐藏手机号码，除了前面3位、末尾2位，其余变成 *
 * @param {*} number 要处理的手机号
 */
function hidePhoneNumber(number) {
    let num = number + "";
    let len = num.length;
    if (len < 5) return num;

    let head = num.slice(0,3);
    let tail = num.slice(len-2);
    let inner = "*".repeat(len-5);
    return `${head}${inner}${tail}`
}

/**
 * 'yyyy-MM-dd HH:mm:ss'格式的字符串转日期
 * @param {*} str 要转换的字符串
 */
function stringToDateTime(str){

    let tempStrs = str.split(" ");

    let dateStrs = tempStrs[0].split("-");

    let year = parseInt(dateStrs[0], 10);

    let month = parseInt(dateStrs[1], 10) - 1;

    let day = parseInt(dateStrs[2], 10);

    let timeStrs = tempStrs[1].split(":");

    let hour = parseInt(timeStrs [0], 10);

    let minute = parseInt(timeStrs[1], 10);

    let second = parseInt(timeStrs[2], 10);
    if(!second ||  isNaN(second)) second = 0;
    
    let date = new Date(year, month, day, hour, minute, second);

    return date;

}


function dateTimeToTime(str, needSecond = false) {
	let date = stringToDateTime(str);
	let hour = date.getHours()
	let minute = date.getMinutes()
	let second = date.getSeconds()
	
	let result;
	if (needSecond) {
		result = [hour, minute, second].map(_normalizeNumber).join(':');
	} else {
		result = [hour, minute].map(_normalizeNumber).join(':');
	}
	return result;
	
}
//计算时间
function calcWaitTime(startTimeStr,isFomart) {
		let now = new Date();
		let startTime = stringToDateTime(startTimeStr);
		let interSec = ((now.getTime()-startTime.getTime())/1000).toFixed(0);
		if(isFomart){
			//默认超时时间位17分钟 60*17
			let timeOutTime=1020;
			if(interSec<timeOutTime){
				interSec=timeOutTime-interSec;
				//小于17分钟，做倒计时
				let interMin = parseInt(interSec /60);
				interSec = interSec - interMin*60;
				interMin = _normalizeNumber(interMin);
				interSec = _normalizeNumber(interSec);
				if(interMin<parseInt(4)){
					return `临${interMin}分${interSec}秒`;
				}
				return `${interMin}分${interSec}秒`;
			}
			if(interSec>timeOutTime){
				console.log("bef",interSec)
				interSec=interSec-timeOutTime;
				let interMin = parseInt(interSec /60);
				interSec = interSec - interMin*60;
				interMin = _normalizeNumber(interMin);
				interSec = _normalizeNumber(interSec);
				return `超${interMin}分${interSec}秒`;
			}
		}


		let interMin = parseInt(interSec /60);
		interSec = interSec - interMin*60;
		interMin = _normalizeNumber(interMin);
		interSec = _normalizeNumber(interSec);
		return `${interMin}分${interSec}秒`;
}


// function _getDateStr(date) {
//     var year = date.getFullYear()
//     var month = date.getMonth() + 1
//     var day = date.getDate()

//     return [year, month, day].map(_normalizeNumber).join('-');
// }

// 解析链接中的参数
function getQueryString (url, name) {
    var reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i')
    var r = url.substr(1).match(reg)
    if (r != null) {
    return r[2]
    }
    return null;
}  

function handleUrlPathVariable(url, data) {
  if (!data) return url;
  for(let key in data) {
    let value = data[key];
    let reg = new RegExp(`({${key}})`, 'gi');
    url = url.replace(reg, value);
  }
  return url;
}

const axios = require('axios').default;

let _workShopId = null;

function _getWorkShopId() {
	if (!_workShopId) {
    return new Promise( (resolve, reject) => {
			axios({url: api.completeServerHost(api.GetShopId),method: 'GET'})
			.then(res => {
					console.log("INFO ==> get shopId from server returned: ", res);
					if (res.status == 200) {
							if (res.data.errcode == 0) {
									_workShopId = res.data.data;
									resolve(res.data.data);
							} else {
									console.log("ERROR ==> get shopId server return error：", res);
									reject(res)
							}
					} else {
							console.log("ERROR ==> get shopId server failed:", res);
							reject(res);
					}
			})
			.catch(err => {
					console.log("ERROR ==> get shopId from server exception: ", err);
					reject(err);
			})
		})
	} else {
		console.log("INFO ==> get shopId from saved variable: ", _workShopId);
		return Promise.resolve(_workShopId);
	}
}

/**
 * 封装的的request
 * 
 * @param {String} url 要访问的服务器URL地址
 * @param {Object} data 需要传给服务器的JSON对象输入数据 
 * @param {String} method POST/GET/PUT/DELETE 等请求方法，默认为 POST
 * @param {String} header HTTP header， 默认为 "application/x-www-form-urlencoded"
 * @param {Boolean} keepSilence 是否弹出“加载中”提示框，默认为 false。如果设置为 true 则无提示框
 * @param {Boolean} allowAnonymous 是否允许匿名调用，默认为 false。如果设置为 true，则服务器要求登录时，不会跳转到登录页面
 */
function request(pageInstance, url, data = {}, method = "POST", contenType = "application/json") {

		Message({type:"info", message:"加载中...", duration:0});
		
		if (!data) data = {};

    return new Promise( (resolve, reject) => {
				_getWorkShopId()
				.then(res => {
					data.shopId = res;
					url = api.completeServerHost(handleUrlPathVariable(url, data));
					console.log(`INFO ==> call http-request[${method}]`, url, arguments)
					axios({
							url: url,
							data: data,
							method: method,
							headers: {
									'Content-Type': contenType,
									'X-Liangshisq-Token' : window.localStorage.getItem("token"),
							},
					})
					.then(res => {
							Message.closeAll();
							console.log("INFO ==>  request succeed!", res)
							if (parseInt(res.status/100) == 2) {
									if (res.data.errcode == 0 ){
											resolve(res.data);
									} else {
											console.log("ERROR ==> http-request application error!", res.data)
											reject(res)
									}
							}  else {
									console.log("ERROR ==> http-request system error!", res)
									reject(res);
							}
					})
					.catch(err => {
							Message.closeAll();
							if (err.response.status == 401) {
									if (pageInstance) {
										goLoginPage(pageInstance);
									}
									console.log("WARN ==>  http-request need authorization", res.data)
									reject(err.response);
									return;
							}
							console.log("ERROR ==> http-request failed!", err)
							reject(err.response);
					})
				})
				.catch(err => {
						Message.closeAll();
						reject(err);
				})
    });
}

/**
 * 获取服务器地址
 */
function getServerHost() {
	let serverHost = window.localStorage.getItem("serverHost");
	if (!serverHost) {
		serverHost = window.location.host;
	}
	return serverHost;
}

/**
 * 跳转到登录页面
 */
function goLoginPage(pageInstance){
   pageInstance.$router.replace({name: "login"});
}

/**
 * 获取当前登录用户
 */
function getCurLoginUser() {
	let userStr = window.localStorage.getItem("user");
	let user = safeParseJson(userStr);
	if (!user) {
		this.$router.replace({name: "login"});
		return null;
	}
	return user;
}

/**
 * 注销登录，删除登录缓存信息
 */
function logout() {
	let serverHost = window.localStorage.getItem("serverHost");
	window.localStorage.clear(); 
	if (serverHost) {
		window.localStorage.setItem("serverHost",serverHost); 
	}
}

/** 
 * 播放声音
 * @param {Object} topic 待播放的声音主题
 * @param {Object} msg 播放消息内容
 */
function playSound(topic, msg) {
	let text;
	if (topic == api.WS_REFRESH_PREPARE) {
			text = "刷新配菜页面，请关注" + msg;
	} else if (topic == api.WS_REFRESH_PASSON) {
			text = "刷新传菜页面，请关注" + msg;
	} else {
		console.log("invalid topic, must be one of ", api.WS_REFRESH_PREPARE, api.WS_REFRESH_PASSON)
		return;
	}
		
	let url = "http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&text=" + encodeURI(text);
	const audio = new Audio(url);
	audio.src = url;
	audio.play();
}

function handelOrderForKitchen(orders, status) {
	if (!orders || !orders.length) return [];
	
	let result = [];
	for(let i=0, len=orders.length; i<len; i++) {
		let order = orders[i];
		let statusOrigQty = 0;
		let statusLastQty = 0;
		let hasCancelledItem = false;
		
		if (!order.items) continue;
		let idxForDelete = [];
		let items = order.items;
		for(let j=0, len2=items.length; j<len2; j++) {
			let item = items[j];
			if (item.status === status) {
				statusOrigQty += item.origQty;
				statusLastQty += item.lastQty;
			} else {
				idxForDelete.push(j);
			}
			if (item.origQty > item.lastQty) {
				hasCancelledItem = true;
			}
		}
		for (let i=idxForDelete.length; i>0; i--) {
			items.splice(idxForDelete[i-1], 1);
		}
		order.origQty = statusOrigQty;
		order.lastQty = statusLastQty;
		order.twinkle = hasCancelledItem; //目前只支持退单闪烁，故两者相同
		order.minusFlag = hasCancelledItem;	//目前只支持退单闪烁，故两者相同
		order.merged = false;
		
		order.shortOrderTime = dateTimeToTime(order.orderTime, false);
		if (statusOrigQty > 0) {
			result.push(order);
		}
	}
	
	return result;
}


export default {
    formatTime,
    formatNumber,
		stringToDateTime,
		dateTimeToTime,
		calcWaitTime,
    request,
    safeParseJson,
    handleNullStr,
    hidePhoneNumber,
    getQueryString,
		getServerHost,
    goLoginPage,
		getCurLoginUser,
		logout,
		playSound,
		handelOrderForKitchen,
		_normalizeNumber
}
